<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2. 分 k 组后排序 </title>
</head>

<body>
  <script>

    var reverseKGroup = function (head, k) {
      if (head == null) return null;
      // 区间 [a, b) 包含 k 个待反转元素
      let a, b;
      a = b = head;
      for (let i = 0; i < k; i++) {
        // 不足 k 个，不需要反转
        if (b == null) return head;
        b = b.next;
      }
      // 反转前 k 个元素
      let newHead = reverse(a, b);
      // 递归反转后续链表并连接起来
      a.next = reverseKGroup(b, k);
      return newHead;
    };
    console.log(reverseKGroup([1, 2, 3, 4, 5], 2))
  </script>
</body>

</html>